<template>
  <div class="warehouse-container">
    <!--div class="toolbar">
      <button @click="zoomIn">+</button>
      <button @click="zoomOut">-</button>
    </div-->
    <div class="svg-container">
      <svg :width="width" :height="height" @wheel="handleZoom" @mousedown="startDrag" @mousemove="drag" @mouseup="stopDrag">
        <g :transform="`translate(${translateX}, ${translateY}) scale(${scale})`">
          <!-- 仓库边界 -->
          <rect v-if="map" :x="map.x" :y="map.y" :width="map.width" :height="map.height" :stroke="map.stroke" :fill="map.fill" :stroke-width="map.strokeWidth" />

          <!-- 栅格 -->
          <g v-for="(cell, index) in mapGrid" :key="11000 + index">
            <line v-if="cell" :x1="cell.x1" :y1="cell.y1" :x2="cell.x2" :y2="cell.y2" stroke="lightgray" stroke-width="1" />
          </g>

          <!-- 标尺 -->
          <g v-for="(cell, index) in mapScale" :key="10000 + index">
            <text v-if="cell" :x="cell.x" :y="cell.y" :text-anchor="cell.textAnchor" :font-size="cell.fontSize" :fill="cell.color">
                {{ cell.text }}
              </text>
          </g>

          <!-- 钢卷 -->
            <g v-for="(cell, index) in mapData" :key="index" @click="showRollInfo(cell)">
              <rect v-if="cell" :x="cell.x" :y="cell.y" :width="cell.width" :height="cell.height" :fill="cell.color" />
            </g>
        </g>
      </svg>
    </div>
    <div class="drawer-toggle" @click="toggleDrawer">
      <div class="toggle-button"></div>
    </div>
    <el-drawer
      title="综合查询"
      :visible.sync="isDrawerOpen"
      direction="rtl"
      size="30%"
      :before-close="handleBeforeClose"
    >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!--el-form-item label="父ID" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入父ID" clearable />
        </el-form-item-->
        <el-form-item label="地图信息" prop="warehouseTotalLocate">
          <el-select v-model="form.warehouseMapName" placeholder="请选择库区信息" style="width: 300px;" clearable @change="handleChangeWarehouseMap">
            <el-option
              v-for="dict in mapOptions"
              :key="dict.mapId"
              :label="dict.warehouseTotalLocate"
              :value="dict.warehouseTotalLocate"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--el-form-item label="园区信息" prop="logisticsParkName">
          <el-input v-model="form.logisticsParkName" placeholder="请输入园区信息" clearable />
        </el-form-item>
        <el-form-item label="仓位信息" prop="warehouseLocateName">
          <el-input v-model="form.warehouseLocateName" placeholder="请输入仓位信息" clearable />
        </el-form-item-->
        <el-form-item label="区位信息" prop="regionLocateName">
          <el-select v-model="form.regionLocateName" placeholder="请选择区位信息" style="width: 300px;" clearable @change="handleChangeRegionLocate">
            <el-option
              v-for="dict in regionLocateOptions"
              :key="dict.locateId"
              :label="dict.name"
              :value="dict.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="货位信息" prop="goodsLocateName">
          <el-select v-model="form.goodsLocateName" placeholder="请选择货位信息" style="width: 300px;" clearable @change="handleChangeGoodsLocate">
            <el-option
              v-for="dict in goodsLocateOptions"
              :key="dict.locateId"
              :label="dict.name"
              :value="dict.name"
            ></el-option>
          </el-select>

        </el-form-item>
        <!--el-form-item label="层位信息" prop="layerLocateName">
          <el-input v-model="form.layerLocateName" placeholder="请输入层位信息" clearable />
        </el-form-item-->

        <el-form-item label="捆包号" prop="bundleNumber">
          <el-input v-model="form.bundleNumber" placeholder="请输入捆包号" clearable style="width: 300px;" />
        </el-form-item>
        <el-form-item label="重量(吨)" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量(吨)" clearable style="width: 300px;" />
        </el-form-item>
        <el-form-item label="库存状态" prop="inventoryStatus">
          <el-select v-model="form.inventoryStatus" placeholder="请选择库存状态" style="width: 300px;" clearable>
            <el-option
              v-for="dict in inventoryStatusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.label"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="drawer-buttons">
        <el-button @click="handleReset">重 置</el-button>
        <el-button type="primary" @click="handleSearch">搜 索</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getMapData } from "@/api/locates/data";
import { getMapScale } from "@/api/locates/scale";
import { getMapGrid } from "@/api/locates/grid";
import { getMap, listMapOption } from "@/api/locates/map";
import { listCustomerOption } from "@/api/customs/custom";
import { listLocateOption } from "@/api/locates/locate";
import { isNotNull } from "@/utils/validate";

export default {
  name: 'SteelRollWarehouse',
  data() {
    return {
      width: window.innerWidth,
      height: window.innerHeight,
      scale: 1,
      translateX: 0,
      translateY: 0,
      isDragging: false,
      lastMouseX: 0,
      lastMouseY: 0,
      mapData: null,
      mapScale: null,
      mapGrid: null,
      map: null,
      refreshIntervalId: null, // 新增属性，用于存储定时器ID
      parentId: null,
      warehouseMapName: null,
      logisticsParkName: null,
      warehouseLocateName: null,
      isDrawerOpen: false,
      // 查询参数
      queryParams: {
        parentId: null,
        warehouseMapName: null,
        warehouseTotalLocate: null,
        logisticsParkName: null,
        warehouseLocateName: null,
        regionLocateName: null,
        goodsLocateName: null,
        layerLocateName: null,
        bundleNumber: null,
        weight: null,
        inventoryStatus: null,
      },
      // 表单参数
      form: {},
      // 字典项客户
      customerOptions: [],
      // 字典项地图
      mapOptions: [],
      // 字典项园区信息
      parkLocateOptions: [],
      // 字典项仓位信息
      warehouseLocateOptions: [],
      // 字典项区位信息
      regionLocateOptions: [],
      // 字典项货位信息
      goodsLocateOptions: [],
      // 字典项库存状态
      inventoryStatusOptions: [],
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    //console.log("created", this.width, this.height);
    const urlParams = new URLSearchParams(window.location.search); // 获取URL中的参数
    const mapId = urlParams.get('mapId') || '1';
    const warehouseMapName = urlParams.get('warehouseMapName') || '';
    const logisticsParkName = urlParams.get('logisticsParkName') || '海泰库';
    const warehouseLocateName = urlParams.get('warehouseLocateName') || '1库';
//    console.log("mapId", mapId);
//    console.log("logisticsParkName", logisticsParkName);
//    console.log("warehouseLocateName", warehouseLocateName);
    this.parentId = mapId;
    this.warehouseMapName = warehouseMapName;
    this.logisticsParkName = logisticsParkName;
    this.warehouseLocateName = warehouseLocateName;

    this.queryParams.parentId = mapId;
    this.queryParams.warehouseMapName = warehouseMapName;
    this.queryParams.logisticsParkName = logisticsParkName;
    this.queryParams.warehouseLocateName = warehouseLocateName;
    this.getList();
    this.getOption();
  },
  computed: {
  },
  mounted() {
    // 监听窗口大小变化
    window.addEventListener('resize', this.updateDimensions);
    // 设置定时器，每120000毫秒（2分钟）调用一次refreshData方法
    this.refreshIntervalId = setInterval(this.refreshData, 120000);
  },
  beforeUnmount() {
    // 移除监听器
    window.removeEventListener('resize', this.updateDimensions);
    // 清除定时器
    clearInterval(this.refreshIntervalId);
  },
  methods: {
    /** 查询仓位地图列表 */
    getList() {
      getMap(this.queryParams.parentId).then(response => {
      this.map = response.data;
      //console.log("map", this.map);
      this.centerImage();
      });
      getMapData(this.queryParams).then(response => {
        this.mapData = response.data;
        //console.log("mapData", this.mapData);
      });
      getMapScale(this.queryParams.parentId).then(response => {
        this.mapScale = response.data;
        //console.log("mapScale", this.mapScale);
      });
      getMapGrid(this.queryParams.parentId).then(response => {
        this.mapGrid = response.data;
        //console.log("mapGrid", this.mapGrid);
      });
    },
    showRollInfo(roll) {
      if (roll) {
        this.$modal.msgSuccess(`钢卷编号: ${roll.bundleNumber}, 库位: ${roll.warehouseTotalLocate}，库存状态：${roll.inventoryStatus}`);
      }
    },
    handleZoom(event) {
      event.preventDefault();
      const delta = event.deltaY < 0 ? 1.6 : 0.5;
      this.scale *= delta;
      this.translateX -= (event.clientX - this.translateX) * (delta - 1);
      this.translateY -= (event.clientY - this.translateY) * (delta - 1);
    },
    startDrag(event) {
      this.isDragging = true;
      this.lastMouseX = event.clientX;
      this.lastMouseY = event.clientY;
    },
    drag(event) {
      if (this.isDragging) {
        this.translateX += event.clientX - this.lastMouseX;
        this.translateY += event.clientY - this.lastMouseY;
        this.lastMouseX = event.clientX;
        this.lastMouseY = event.clientY;
      }
    },
    stopDrag() {
      this.isDragging = false;
    },
    zoomIn() {
      this.scale *= 1.5;
    },
    zoomOut() {
      this.scale *= 0.5;
    },
    centerImage() {
      const containerWidth = this.width;
      const containerHeight = this.height;
      const contentWidth = this.map.mapWidth;
      const contentHeight = this.map.mapHeight;

      // 计算初始缩放比例
      const scaleX = containerWidth / contentWidth;
      const scaleY = containerHeight / contentHeight;
      this.scale = Math.min(scaleX, scaleY);

      // 计算初始位置
      this.translateX = (containerWidth - contentWidth * this.scale) / 2;
      this.translateY = (containerHeight - contentHeight * this.scale) / 2;
    },
    updateDimensions() {
      this.width = window.innerWidth;
      this.height = window.innerHeight;
      this.centerImage(); // 更新尺寸后重新居中图片
    },
    refreshData() {
      console.log("refreshData");
      getMapData(this.queryParams).then(response => {
        this.mapData = response.data;
        //console.log("mapData", this.mapData);
      });
    },
    toggleDrawer() {
      this.isDrawerOpen = !this.isDrawerOpen;
//      this.handleReset();
      this.form = {
        parentId: this.queryParams.parentId,
        warehouseMapName: this.queryParams.warehouseMapName,
        warehouseTotalLocate: this.queryParams.warehouseTotalLocate,
        logisticsParkName: this.queryParams.logisticsParkName,
        warehouseLocateName: this.queryParams.warehouseLocateName,
        regionLocateName: this.queryParams.regionLocateName ? this.queryParams.regionLocateName : '',
        goodsLocateName: this.queryParams.goodsLocateName ? this.queryParams.goodsLocateName : '',
        layerLocateName: this.queryParams.layerLocateName,
        bundleNumber: this.queryParams.bundleNumber,
        weight: this.queryParams.weight,
        inventoryStatus: this.queryParams.inventoryStatus,
      };
      this.handleLoadOptions();
    },
    handleBeforeClose(done) {
      done();
    },
    handleSearch() {
      this.queryParams = {
        parentId: this.form.parentId,
        warehouseMapName: this.form.warehouseMapName,
        warehouseTotalLocate: this.form.warehouseTotalLocate,
        logisticsParkName: this.form.logisticsParkName,
        warehouseLocateName: this.form.warehouseLocateName,
        regionLocateName: this.form.regionLocateName,
        goodsLocateName: this.form.goodsLocateName,
        layerLocateName: this.form.layerLocateName,
        bundleNumber: this.form.bundleNumber,
        weight: this.form.weight,
        inventoryStatus: this.form.inventoryStatus,
      }
      // 执行搜索逻辑
      this.getList();
      // 关闭抽屉
      this.isDrawerOpen = false;
    },
    handleReset() {
      this.form = {
        parentId: this.parentId,
        warehouseMapName: this.warehouseMapName,
        warehouseTotalLocate: null,
        logisticsParkName: this.logisticsParkName,
        warehouseLocateName: this.warehouseLocateName,
        regionLocateName: '',
        goodsLocateName: '',
        layerLocateName: '',
        bundleNumber: null,
        weight: null,
        inventoryStatus: null,
      };
      this.resetForm("form");
      this.handleLoadOptions();
    },
    getOption() {
      /** 字典项客户*/
      listCustomerOption().then(response => {
        this.customerOptions = response.data;
      });
      /** 字典项园区 */
      listMapOption().then(response => {
        this.mapOptions = response.data;
      });
      /** 字典项园区 */
      listLocateOption(0).then(response => {
        this.parkLocateOptions = response.data;
//        console.log('this.parkLocateOptions',this.parkLocateOptions);
      });
      /** 字典项库存状态 */
      this.inventoryStatusOptions.push({label: '已在库', value: 0});
      this.inventoryStatusOptions.push({label: '出库中', value: 1});
//      this.inventoryStatusOptions.push({label: '货转中', value: 2});
    },
    handleChangeLogisticsPark(value) {
//      console.log('handleChangeLogisticsPark', value);
//      console.log('this.$refs.optionRef.selected.value', this.$refs.optionRef.selected.value);
//      console.log('this.$refs.optionRef.selected.label', this.$refs.optionRef.selected.label);
//      console.log('this.$refs.optionRef.selected.key', this.$refs.optionRef.selected.key);
      let park = {};
      park = this.parkLocateOptions.find((item) => {
        return item.name === value; //筛选出匹配数据
      });
//      console.log('park', park);
//      this.form.logisticsParkName = value.name;
//      console.log('handleChangeLogisticsPark', label);
      /** 字典项仓库 */
      listLocateOption(park.locateId).then(response => {
        this.warehouseLocateOptions = response.data;
        this.regionLocateOptions = {};
        this.goodsLocateOptions = {};
        this.form.warehouseLocateName = '';
        this.form.regionLocateName = '';
        this.form.goodsLocateName = '';
        this.form.warehouseTotalLocate = '';
        this.form.warehouseType = '';
//        console.log('this.warehouseLocateOptions',this.warehouseLocateOptions);
      });
    },
    handleChangeWarehouseLocate(value) {
//      console.log('handleChangeWarehouse', value);
      let warehouse = {};
      warehouse = this.warehouseLocateOptions.find((item) => {
        return item.name === value; //筛选出匹配数据
      });
//      this.$set(this.form, 'warehouseType', warehouse.warehouseType);
//      console.log('warehouse', warehouse);
      /** 字典项区位 */
      listLocateOption(warehouse.locateId).then(response => {
        this.regionLocateOptions = response.data;
        this.goodsLocateOptions = {};
        this.form.regionLocateName = '';
        this.form.goodsLocateName = '';
//        console.log('this.regionLocateOptions',this.regionLocateOptions);
      });
      this.handleChangeGoodsLocate();
    },
    handleChangeRegionLocate(value) {
//      console.log('handleChangeWarehouse', value);
      let region = {};
      region = this.regionLocateOptions.find((item) => {
        return item.name === value; //筛选出匹配数据
      });
//      console.log('region', region);
      /** 字典项货位 */
      listLocateOption(region.locateId).then(response => {
        this.goodsLocateOptions = response.data;
        this.form.goodsLocateName = '';

//        console.log('this.goodsLocateOptions',this.goodsLocateOptions);
      });
      this.handleChangeGoodsLocate();
    },
    handleChangeGoodsLocate(value) {
      this.form.warehouseTotalLocate = this.form.logisticsParkName + this.form.warehouseLocateName + this.form.regionLocateName + this.form.goodsLocateName;
    },
    //
    handleLoadOptions(){
//      if(this.form.logisticsParkName != ''){
      if(isNotNull(this.form.logisticsParkName)){
//        console.log("this.form.logisticsParkName = ", this.form.logisticsParkName);
        let park = {};
        park = this.parkLocateOptions.find((item) => {
          return item.name === this.form.logisticsParkName; //筛选出匹配数据
        });
        /** 字典项仓库 */
        listLocateOption(park.locateId).then(response => {
          this.warehouseLocateOptions = response.data;

          if (this.form.warehouseLocateName != '') {
//            console.log("this.form.warehouseLocateName = ", this.form.warehouseLocateName);
            let warehouse = {};
            warehouse = this.warehouseLocateOptions.find((item) => {
              return item.name === this.form.warehouseLocateName; //筛选出匹配数据
            });
            /** 字典项区位 */
            listLocateOption(warehouse.locateId).then(response => {
              this.regionLocateOptions = response.data;
              if (this.form.regionLocateName != '') {
//                console.log("this.form.regionLocateName = ", this.form.regionLocateName);
                let region = {};
                region = this.regionLocateOptions.find((item) => {
                  return item.name === this.form.regionLocateName; //筛选出匹配数据
                });
                /** 字典项货位 */
                listLocateOption(region.locateId).then(response => {
                  this.goodsLocateOptions = response.data;
                });
              } else {
                // 清除货位字典项
//                console.log("clear goodsLocateOptions");
                this.goodsLocateOptions = {};
              }
            });
          }
        });
      }
    },
    handleChangeWarehouseMap(value) {
      let map = {};
      map = this.mapOptions.find((item) => {
        return item.warehouseTotalLocate === value; //筛选出匹配数据
      });
      this.form.parentId = map.mapId;
      this.form.logisticsParkName = map.logisticsParkName;
      this.form.warehouseLocateName = map.warehouseLocateName;
      this.form.regionLocateName = '';
      this.form.goodsLocateName = '';

      this.handleLoadOptions();
    }
  }
};
</script>

<style scoped>
.warehouse-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: hidden;
}

.toolbar {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
}

.svg-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

svg {
  border: 1px solid #ccc;
  cursor: grab;
}

svg:active {
  cursor: grabbing;
}

.drawer-toggle {
  position: absolute;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  width: 10px;
  height: 60px;
  background-color: #007bff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  border-radius: 4px 0 0 4px;
}

.toggle-button::before {
  content: '+';
  font-size: 20px;
}

.drawer-buttons {
  margin-top: auto;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.drawer-content {
  padding: 20px;
}
</style>